package com.tws.pctask.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tws.common.enums.ResultEnum;
import com.tws.common.model.ResponseWrapper;
import com.tws.dao.entity.User;
import com.tws.dao.entity.UserIdentity;
import com.tws.dao.entity.UserState;
import com.tws.dao.mapper.UserMapper;
import com.tws.pctask.mapper.RegisterMapper;
import com.tws.pctask.model.registerManageModel.*;
import com.tws.pctask.model.userManageModel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Description： 用户管理服务层
 * @Author: wbf
 * @Date: 2022/1/21 13:56
 */
@Service
public class UserManageService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 3.1获取用户身份列表
     * @return 身份列表
     */
    public ResponseWrapper getUserIdentityList(){
        return ResponseWrapper.markSuccess(UserIdentity.dataList);
    }

    /**
     * 3.2获取用户状态列表
     * @return 状态列表
     */
    public ResponseWrapper getUserStateList(){
        return ResponseWrapper.markSuccess(UserState.dataList);
    }

    /**
     * 3.3获取用户列表
     * @param param 关键字查询和分页参数
     * @return 用户列表
     */
    public ResponseWrapper getUserList(GetUserListParam param){
        if(param.getSearchKey() == null){param.setSearchKey("");}
        LambdaQueryWrapper<User> selectCondition = new LambdaQueryWrapper<>();
        IPage<User> userIPage = new Page<>(param.getPage(),param.getPageSize());
        if(param.getSearchKey() != null && !param.getSearchKey().equals("")){
            selectCondition
                    .like(User::getUserEmail,param.getSearchKey())
                    .or()
                    .like(User::getUserName,param.getSearchKey());
        }
        if(param.getUserState() != null){
            selectCondition.eq(User::getUserState,param.getUserState());
        }
        if(param.getUserIdentity() != null){
            selectCondition.eq(User::getUserIdentity,param.getUserIdentity());
        }

        IPage<User> users = userMapper.selectPage(userIPage,selectCondition);
        List<User> userList = users.getRecords();
        List<GetUserListItem> item = JSON.parseArray(JSON.toJSONString(userList),GetUserListItem.class);

        for(int i = 0; i < item.size(); i++){
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd hh-mm-ss");
            item.get(i).setCreateTime(df.format(userList.get(i).getCreateTime()));
            item.get(i).setUpdateTime(df.format(userList.get(i).getUpdateTime()));

            //填充用户的状态和身份
            String userIdentity = item.get(i).getUserIdentity();
            int id = Integer.parseInt(userIdentity);
            userIdentity =  UserIdentity.dataMap.get(id).getIdentityName();
            item.get(i).setUserIdentity(userIdentity);
            id = Integer.parseInt(item.get(i).getUserState());
            String stateName = UserState.dataMap.get(id).getStateName();
            item.get(i).setUserState(stateName);
        }

        Long rowsNum = userMapper.selectCount(selectCondition).longValue();
        Long userNum = userMapper.selectCount(null).longValue();
        System.out.println(item);
        return ResponseWrapper.markSuccess(new GetUserListResult(item,rowsNum,userNum));
    }

    /**
     * 3.4检查用户名是否重复
     * @param param 用户名
     * @return true为重复 false为不重复
     */
    public ResponseWrapper checkName(CheckNameParam param){
        LambdaQueryWrapper<User> selectByName = new LambdaQueryWrapper<>();
        selectByName.eq(User::getUserName,param.getUserName());
        User user = userMapper.selectOne(selectByName);
        CheckNameResult result = new CheckNameResult(user != null);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 3.5检查邮箱是否重复
     * @param param 邮箱
     * @return true为重复 false为不重复
     */
    public ResponseWrapper checkEmail(CheckEmailParam param){
        LambdaQueryWrapper<User> selectByEmail = new LambdaQueryWrapper<>();
        selectByEmail.eq(User::getUserEmail,param.getUserEmail());
        User user = userMapper.selectOne(selectByEmail);
        CheckEmailResult result = new CheckEmailResult(user != null);
        return ResponseWrapper.markSuccess(result);
    }
    @Autowired
    RegisterMapper registerMapper;
    /**
     * 3.6新增或修改用户
     * @param param 对应用户参数
     * @return 结果在数据库中查看
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper addOrUpdateUser(AddOrUpdateUserParam param){
        User newUser = JSON.parseObject(JSON.toJSONString(param),User.class);
        if(newUser.getUserId().equals("-1")){
            /**
             * 用户名和邮箱查重
             */
            CheckNameResult nameResult = (CheckNameResult) checkName(new CheckNameParam(param.getUserName())).getData();
            if(nameResult.getIsExist()){return ResponseWrapper.markError(ResultEnum.USER_EXISTS);}
            CheckEmailResult emailResult = (CheckEmailResult)checkEmail(new CheckEmailParam(param.getUserEmail())).getData();
            if(emailResult.getIsExist()){return ResponseWrapper.markError(ResultEnum.USER_EMAIL_EXISTS);}

            //生成id
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter df = DateTimeFormatter.ofPattern("MMdd");
            String currentTime = df.format(now);
            String userId = currentTime+ IdUtil.randomUUID().split("-")[0];
            newUser.setUserId(userId);
            //插入用户
            userMapper.insert(newUser);
            //创建用户相关表
            if(newUser.getUserIdentity() != 0) {
                registerMapper.creatDepartmentTable(new CreatTables(newUser.getUserId()));//创建用户相关表
            }
        }
        else{
            userMapper.updateById(newUser);
        }
        return ResponseWrapper.markSuccess(newUser);
    }

    /**
     * 3.7获取用户的信息
     * @param param 用户id
     * @return 指定用户的信息
     */
    public ResponseWrapper getUserInfo(GetUserInfoParam param){
        User user = userMapper.selectById(param.getUserId());
        GetUserInfoResult result = JSON.parseObject(JSON.toJSONString(user),GetUserInfoResult.class);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 3.8删除用户
     * @param param 用户id
     * @return 数据库查看结果
     */
    @Transactional(rollbackFor = Exception.class)
    public ResponseWrapper delUser(DelUserParam param){
        userMapper.deleteById(param.getUserId());
        registerMapper.deleteDepartmentTable(new CreatTables(param.getUserId()));
        return ResponseWrapper.markSuccess();
    }

    /**
     * 3.9每日零点定时执行deadline-1
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void subDeadline(){
        List<User> users = userMapper.selectList(null);
        for (User each : users) {
            if(each.getDeadline() > 0){
                int deadline = each.getDeadline() - 1;
                if(deadline < 1){ //如果用户时限用完 更改状态
                    each.setUserState(1);
                }
                each.setDeadline(deadline);
                userMapper.updateById(each);
            }
        }
    }
}
